/**
 * 1.0.1
 */
package com.ruoyi.server.util;

public class ByteUtil {
    static byte[] mask = new byte[128];

    static {
        initMask();
    }

    static byte[] asciiMask = new byte[]{'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    private static void initMask() { // init mask
        for (int i = 0; i <= 9; i++) {
            mask[i + 48] = (byte) i;
        }
        for (int i = 0; i <= 5; i++) {
            mask[i + 97] = (byte) (10 + i);
        }
        for (int i = 0; i <= 5; i++) {
            mask[i + 65] = (byte) (10 + i);
        }
    }

    public static byte[] hexStr2Byte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    public static String hexToStr(byte[] buf) {
        return hexToStr(buf, 0, buf.length);
    }

    public static String hexToStr(byte b) {
        byte[] buf = new byte[1];
        buf[0] = b;
        return hexToStr(buf, 0, buf.length);
    }

    public static String hexToStr(byte[] buf, int idx, int len) {
        StringBuffer sb = new StringBuffer();
        int n;
        for (int i = 0; i < len; i++) {
            n = buf[i + idx] & 0xff;
            if (n < 0x10) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(n));
        }

        return sb.toString();
    }

    private static byte toByte(char c) {
        return mask[c];
    }

    public static void main(String[] args) {
        String s = ByteUtil.hexToStr("灸疗床".getBytes());
        System.out.println(s);
        byte[] r = ByteUtil.hexStr2Byte(s);
        System.out.println(new String(r));
    }
}
